package com.jagochan.mall.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jagochan.mall.common.exception.BusinessException;
import com.jagochan.mall.domain.po.Category;
import com.jagochan.mall.domain.vo.CategoryTreeVO;
import com.jagochan.mall.domain.vo.req.CategoryReq;
import com.jagochan.mall.mapper.CategoryMapper;
import com.jagochan.mall.service.CategoryService;
import org.springframework.stereotype.Service;

import java.util.*;


@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Override
    public String saveCategory(CategoryReq req) {
        // 判断名称是否重复
        notDuplicateName(req.getName());

        Category po = BeanUtil.copyProperties(req, Category.class);
        save(po);
        return po.getId() + "";
    }

    private void notDuplicateName(String name) {
        Category po = lambdaQuery().eq(Category::getName, name).one();
        if (po != null) {
            BusinessException.raise("分类名称不能重复");
        }
    }

    @Override
    public List<CategoryTreeVO> listCategoryTreeVO() {
        List<Category> poList = list();
        if (poList.isEmpty()) {
            return Collections.emptyList();
        }

        poList.sort(Comparator.comparing(Category::getParentId));
        Map<Long, CategoryTreeVO> longVoMap = new HashMap<>();
        List<CategoryTreeVO> result = new ArrayList<>();
        for (Category category : poList) {
            CategoryTreeVO vo = BeanUtil.copyProperties(category, CategoryTreeVO.class);
            if (category.getParentId() == 0) { // 根分类
                longVoMap.put(vo.getId(), vo);
                result.add(vo);
            } else {
                CategoryTreeVO parent = longVoMap.get(vo.getParentId());
                List<CategoryTreeVO> children = parent.getChildren();
                if (children == null) {
                    children = new ArrayList<>();
                    parent.setChildren(children);
                }
                children.add(vo);
                longVoMap.put(vo.getId(), vo);
            }
        }

        return result;
    }

}